package service

import (
	"bytes"
	"com.cracker/src/com.cracker/app/model"
	"encoding/base64"
	"encoding/json"
	log "github.com/sirupsen/logrus"
	"io/ioutil"
	"net/http"
	"os/exec"
	"time"
)

type AppService struct {
}

func (appService *AppService) WakeUp(password string) {
	cmd := exec.Command("adb", "shell", "input", "keyevent", "224")
	_, err := cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
	time.Sleep(1 * time.Second)
	cmd = exec.Command("adb", "shell", "input", "swipe", "0", "500", "0", "0")
	_, err = cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
	if password != "" {
		// 解锁
		cmd = exec.Command("adb", "shell", "input", "text", password)
		_, err = cmd.Output()
		if err != nil {
			log.Error(err)
			return
		}
		time.Sleep(1 * time.Second)
		cmd = exec.Command("adb", "shell", "input", "keyevent", "66")
		_, err = cmd.Output()
		if err != nil {
			log.Error(err)
			return
		}
	}
}
func (appService *AppService) AppSleep() {
	cmd := exec.Command("adb", "shell", "input", "keyevent", "223")
	_, err := cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
}
func (appService *AppService) StartApp() {
	time.Sleep(1 * time.Second)
	cmd := exec.Command("adb", "shell", "am", "start", "-S", "com.alibaba.android.rimet/.biz.LaunchHomeActivity")
	_, err := cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
}
func (appService *AppService) getScreen(uid string, address string) {
	pngpath := "/sdcard/screencap.png"
	localpath := "./screencap.png"
	cmd := exec.Command("adb", "shell", "screencap", "-p", pngpath)
	_, err := cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
	cmd = exec.Command("adb", "pull", pngpath, localpath)
	_, err = cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
	cmd = exec.Command("adb", "shell", "rm", pngpath)
	_, err = cmd.Output()
	if err != nil {
		log.Error(err)
		return
	}
	log.Warn("截图完毕")
	go appService.upload(uid, address)
}

func (appService *AppService) upload(uid string, address string) {
	url := "http://" + address + "/index/screenshot"
	//	picture application/json
	filebytes, err := ioutil.ReadFile("./screencap.png")
	if err != nil {
		log.Error("open file err:", err.Error())
		return
	}

	screenShotModel := &model.ScreenShotModel{}
	screenShotModel.Picture = base64.StdEncoding.EncodeToString(filebytes)
	client := &http.Client{Timeout: 5 * time.Second}
	jsonBytes, _ := json.Marshal(screenShotModel)
	request, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes))
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("uid", uid)
	_, err = client.Do(request)
	if err != nil {
		log.Error(err)
		return
	}
}
